package com.guet.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guet.domain.Blog;
import com.guet.domain.Follow;
import com.guet.domain.User;
import com.guet.domain.dto.ScrollResult;
import com.guet.domain.dto.UserDTO;
import com.guet.mapper.BlogMapper;
import com.guet.service.BlogService;
import com.guet.service.FollowService;
import com.guet.service.UserService;
import com.guet.utils.Result;
import com.guet.utils.SystemConstants;
import com.guet.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static com.guet.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.guet.utils.RedisConstants.FEED_KEY;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogMapper blogMapper;
    @Resource
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private FollowService followService;

    @Override
    public Result save(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        blog.setLiked(0);
        // 保存探店博文
        boolean isSuccess = blogMapper.save(blog);
        if(!isSuccess){
            return Result.fail("新增笔记失败!");
        }
        // 查询作者的粉丝,并将文章推送到每一位粉丝
        List<Follow> fans = followService.getFans(user.getId());
        for (Follow fan : fans) {
            // 粉丝id
            Long userId = fan.getUserId();
            String key = FEED_KEY + userId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回文章id
        return Result.ok(blog.getId());
    }

    @Override
    public void updateLiked(Long blogId){
        Long userId = UserHolder.getUser().getId();
        String key = BLOG_LIKED_KEY + blogId;
        // 判断当前用户是否已点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if(score == null){
            // 点赞
            boolean isSuccess = blogMapper.updateLiked(1, blogId);
            if(isSuccess){
               stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
        }else {
            // 取消点赞
            boolean isSuccess = blogMapper.updateLiked(-1, blogId);
            if(isSuccess){
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
    }


    @Override
    public List<Blog> myBlog(Long userId, Integer page){
        PageHelper.startPage(page, SystemConstants.MAX_PAGE_SIZE);
        List<Blog> list = blogMapper.getByUserId(userId);
        return list;
    }

    @Override
    public List<Blog> hotBlog(Integer page) {
        PageHelper.startPage(page,SystemConstants.MAX_PAGE_SIZE,"liked desc");
        List<Blog> list = blogMapper.getAll();

        list.forEach(blog -> {
            User user = userService.getById(blog.getUserId());
            blog.setName(user.getNickName());
            blog.setIcon(user.getIcon());
            isBlogLiked(blog);
        });

        return list;
    }

    @Override
    public Result queryBlogById(Long blogId) {
        Blog blog = blogMapper.getById(blogId);
        if(blog == null){
            return Result.fail("笔记不存在");
        }
        User u = userService.getById(blog.getUserId());
        blog.setName(u.getNickName());
        blog.setIcon(u.getIcon());
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    @Override
    public Result queryBlogLikes(Long id) {
        // 查询top5的点赞用户
        String key = BLOG_LIKED_KEY + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(top5 == null || top5.isEmpty()){
            return Result.ok(Collections.emptyList());
        }

        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        List<UserDTO> userDTOS = userService.getByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    @Override
    public Result queryBlogOfFollow(Long lastId, Integer offset) {
        // 当前用户
        Long userId = UserHolder.getUser().getId();

        // 查询收件箱 ZREVRANGEBYSCORE key max min limit offset count
        // rev将score降序排,指定score范围内的元素[lastId,0],从lastId开始取offset和count
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, lastId, offset, 3);
        if(typedTuples == null || typedTuples.isEmpty()){
            return Result.ok();
        }

        List<Long> blogIds = new ArrayList<>(typedTuples.size());
        long minTime = 0;// 最小时间戳(最小score)
        int os = 1;// 最小时间戳一样的元素的个数

        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            // blogId
            blogIds.add(Long.valueOf(Objects.requireNonNull(tuple.getValue())));
            // score
            long time = Objects.requireNonNull(tuple.getScore()).longValue();
            if(time == minTime){
                os++;
            } else {
                minTime = time;
                os = 1;
            }
        }

        List<Blog> blogs = blogMapper.getByIds(blogIds);
        for (Blog blog : blogs) {
            User u = userService.getById(blog.getUserId());
            blog.setName(u.getNickName());
            blog.setIcon(u.getIcon());
            isBlogLiked(blog);
        }

        ScrollResult r = new ScrollResult();
        r.setList(blogs);
        r.setOffset(os);
        r.setMinTime(minTime);
        return Result.ok(r);
    }

    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if(user == null){
            // 用户未登录,无须查询是否点赞
            return;
        }
        Long userId = user.getId();
        String key = BLOG_LIKED_KEY + blog.getId();
        Double score  = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }
}
